package com.mbyte.easy.rest.course;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mbyte.easy.admin.entity.Course;
import com.mbyte.easy.admin.entity.Student;
import com.mbyte.easy.admin.entity.StudentCourse;
import com.mbyte.easy.admin.service.ICourseService;
import com.mbyte.easy.admin.service.IStudentCourseService;
import com.mbyte.easy.admin.service.IStudentService;
import com.mbyte.easy.common.constant.RoleConstant;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.security.entity.SysRole;
import com.mbyte.easy.security.entity.SysUser;
import com.mbyte.easy.security.service.IRoleService;
import com.mbyte.easy.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
* <p>
* 前端控制器
* </p>
* @author lp
* @since 2019-03-11
*/
@RestController
@RequestMapping("rest/course")
public class RestCourseController extends BaseController  {

    @Autowired
    private ICourseService courseService;
    @Resource
    private CacheManager cacheManager;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IStudentCourseService studentCourseService;

    /**
    * 查询列表
    *
    * @param pageNo
    * @param pageSize
    * @param token
    * @return
    */
    @RequestMapping
    public AjaxResult index(@RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo
            ,@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize
            , String token) {

        Cache cache = cacheManager.getCache("serviceCacheToken");
        SysUser user = cache.get(token, SysUser.class);
        if(user != null){
            SysRole sysUserRole = null;
            List<SysRole> sysUserRoles = roleService.selectRolesByUserID(user.getId());
            if(!CollectionUtils.isEmpty(sysUserRoles)){
                sysUserRole = sysUserRoles.get(0);
            }
            Page<Course> page = new Page<Course>(pageNo, pageSize);
            QueryWrapper<Course> queryWrapper = new QueryWrapper<Course>();
            Map<String, Object> map = new HashMap<>();
            if(sysUserRole != null){
                if(sysUserRole.getId().equals(RoleConstant.ROLE_ID_STUDENT)){
                    Student student = studentService.getOne(new LambdaQueryWrapper<Student>()
                            .eq(Student::getStuNumber, user.getUsername()));
                    List<StudentCourse> list = studentCourseService.list(new LambdaQueryWrapper<StudentCourse>()
                            .eq(StudentCourse::getStuId, student.getId()));
                    if(!CollectionUtils.isEmpty(list)){
                        List<Long> ids = new ArrayList<>();
                        for ( StudentCourse studentCourse : list ) {
                            int cid = studentCourse.getCourseId();
                            ids.add((long) cid);
                        }
                        if(!CollectionUtils.isEmpty(ids)){
                            queryWrapper.in("id",ids);
                        }
                    }
                }
            }

            IPage<Course> pageInfo = courseService.page(page , queryWrapper);
            map.put("pageInfo", pageInfo.getRecords());
            return this.success(map);
        }else {
            return error();
        }
    }


    /**
    * 添加
    * @param course
    * @return
    */
    @PostMapping("add")
    public AjaxResult add(Course course){
        return toAjax(courseService.save(course));
    }

    /**
    * 添加
    * @param course
    * @return
    */
    @PostMapping("edit")
    public AjaxResult edit(Course course){
        return toAjax(courseService.updateById(course));
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @GetMapping("delete/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        return toAjax(courseService.removeById(id));
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @PostMapping("deleteAll")
    public AjaxResult deleteAll(@RequestBody List<Long> ids){
        return toAjax(courseService.removeByIds(ids));
    }

}

